<template>
  <el-col :span="isCollapse ? 1 : 3" class="common-aside">
    <div class="menu-container">
      <el-menu
        active-text-color="#ffd04b"
        background-color="#43497B"
        class="el-menu-vertical-demo"
        :collapse="isCollapse"
        :default-active="activeMenu"
        text-color="#fff"
        @select="handleSelect"
      >
        <!-- 图标 -->
        <div style="display: flex; justify-content: center; align-items: center; margin-top: 20px" v-if="!isCollapse">
          <img src="../assets/课表.svg" alt="logo" class="logo" style="width: 40px; height: 40px" />
        </div>
        <h5 class="menu-title">{{ isCollapse ? "课务" : "智能课务平台" }}</h5>
        <template v-for="item in menuData" :key="item.id">
          <el-menu-item :index="item.path" style="text-align: center">
            <component class="icons" :is="item.icon"></component>
            <span>{{ item.title }}</span>
          </el-menu-item>
        </template>
      </el-menu>

      <div class="copyright" :class="{ collapsed: isCollapse }">
        <!-- 状态显示区域 -->
        <!-- 添加二维码区域 -->

        <div v-if="!isCollapse" style="text-align: center; margin-bottom: 20px">点击下方切换<br />小程序码/识别码</div>
        <div v-if="!isCollapse && qrCodeUrl" class="qrcode-container">
          <el-tooltip :content="showQRCode ? '小程序内扫一扫' : '微信扫一扫直接绑定'" placement="right" effect="light">
            <div class="qrcode-wrapper" @click="toggleQRCode">
              <img
                :src="showQRCode ? qrCodeUrl : miniprogramCodeUrl || miniprogramImage"
                :alt="showQRCode ? 'QR Code' : 'Mini Program'"
                class="qrcode-image"
              />
            </div>
          </el-tooltip>
          <div class="qrcode-title" @click="copyQRCode">
            <span>{{ showQRCode ? recognitionCode : "专属小程序码" }}</span>
          </div>
        </div>
        <!-- 这里增加一个状态显示 悬浮显示 点击此处进行解绑 点击后弹出小气泡是否确认，确认就调用解绑接口 -->
        <!-- 微信小程序绑定状态显示区域 -->

        <el-popconfirm
          v-if="!isCollapse"
          title="确定要解绑微信小程序吗？"
          description="解绑后将无法使用小程序相关功能"
          @confirm="handleUnbindClick"
          confirm-button-text="确定"
          cancel-button-text="取消"
          placement="right"
          icon="none"
          center="true"
          :disabled="!wxBindStatus"
        >
          <template #reference>
            <div class="status-group">
              <div class="status-item">
                <span class="value no-dot" :class="{ success: wxBindStatus, error: !wxBindStatus }">
                  {{ wxBindStatus ? "小程序已绑定·解绑" : "小程序未绑定" }}
                </span>
              </div>
            </div>
          </template>
        </el-popconfirm>
        <!-- 状态显示区域 -->
        <el-tooltip
          v-if="!isCollapse"
          effect="dark"
          content="中转数量大于0且MySeig正常时，本平台才支持与MySeig(教务系统)同步相关数据"
          placement="right"
          ><div class="status-group">
            <div class="status-item">
              <span class="label">中转数量：</span>
              <span class="value" :class="{ success: frpStatus > 0, error: frpStatus === 0 }">
                {{ frpStatus }} 个
              </span>
            </div>
            <div class="status-item">
              <span class="label">教务系统：</span>
              <span class="value" :class="{ success: seigStatus, error: !seigStatus }">
                {{ seigStatus ? "正常" : "异常" }}
              </span>
            </div>
          </div>
        </el-tooltip>

        <div class="copyright-content" @click="visible = true">
          <el-tooltip content="点击提交反馈" placement="right" effect="light">
            <div>
              © 2025
              <span v-if="!isCollapse"> 大大怪</span>
            </div>
          </el-tooltip>
          <div style="display: flex; justify-content: center; align-items: center" v-if="!isCollapse">
            <a href="https://github.com/multiavatar/Multiavatar" target="_blank" style="color: #c7c9d8"> Multiavatar </a
            >&nbsp;
            <a href="https://apis.whyta.cn/" target="_blank" style="color: #c7c9d8"> WhyApi </a>
          </div>
        </div>
      </div>
    </div>
  </el-col>
  <el-dialog v-model="visible" title="意见反馈" class="feedback-dialog" :width="dialogWidth" destroy-on-close center>
    <el-form :model="form" :rules="rules" ref="formRef" label-width="60px">
      <!-- 星级评分 -->
      <el-form-item label="评分" prop="rating">
        <el-rate v-model="form.rating" :max="5" show-text />
      </el-form-item>

      <!-- 反馈内容 -->
      <el-form-item label="内容" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="4"
          placeholder="快来提供点建议吧，哪里点得不爽也可以吐个槽，此输入框支持粘贴图片，有啥说啥，欢迎调戏~"
          @paste="handlePaste"
        />
      </el-form-item>

      <!-- 联系方式 -->
      <el-form-item label="联系">
        <el-input v-model="form.contact" placeholder="手机/邮箱（选填）" />
      </el-form-item>

      <!-- 图片上传 -->
      <el-upload
        v-model:file-list="fileList"
        list-type="picture-card"
        :limit="5"
        :auto-upload="false"
        :on-exceed="handleExceed"
        multiple
        style="text-align: center"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>
    </el-form>
    <div style="text-align: center; margin-top: 20px">交流学习可联系：vanderwals@163.com</div>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, computed, watch, onMounted, reactive, onUnmounted } from "vue";
  import { useRoute, useRouter } from "vue-router";
  import { useAllDataStore } from "../stores/index";
  import { defineEmits } from "vue";
  import api from "../axios/api";
  import { ElMessage, ElNotification } from "element-plus";
  // @ts-ignore
  import QRCode from "qrcode";
  // 导入图片
  import miniprogramImage from "../assets/miniprogram.jpg";

  const route = useRoute();
  const router = useRouter();
  const store = useAllDataStore();
  const emit = defineEmits(["updateCollapse"]);

  const seigStatus = ref(false);
  const frpStatus = ref(0);

  const getSeigFrpStatus = async () => {
    const res = await api.getSeigFrpStatus();
    seigStatus.value = res.data.seig_status;
    frpStatus.value = res.data.frp_status;
    console.log(res.data);
  };

  const isCollapse = computed(() => store.state.isCollapse);

  // 监听 isCollapse 的变化并通知父组件
  watch(isCollapse, newVal => {
    emit("updateCollapse", newVal);
  });

  // 当前激活的菜单项
  const activeMenu = ref(route.path);

  interface MenuItem {
    id: number;
    title: string;
    icon: string;
    path: string;
  }

  const menuData = ref<MenuItem[]>([]);

  // 处理菜单选择
  const handleSelect = (index: string) => {
    router.push(index);
  };

  // 监听路由变化，当变化时，更新 activeMenu 的值
  watch(
    () => route.path,
    newPath => {
      activeMenu.value = newPath;
    }
  );

  onMounted(() => {
    // const roleValue = localStorage.getItem('role') || '' // roleValue 是 'role "student"'
    const role = localStorage.getItem("role") || ""; // 提取 "student
    menuData.value = [
      { id: 1, title: "平台首页", icon: "House", path: "/home" },
      { id: 2, title: "查看课表", icon: "Notebook", path: "/myCourse" },
      { id: 4, title: "课表规划", icon: "Grid", path: "/course" },
      { id: 5, title: "组织协同", icon: "Calendar", path: "/myorganization" }
      // { id: 6, title: "测试1", icon: "CirclePlus", path: "/test" }
    ];
    if (role === "admin") {
      menuData.value.push({ id: 3, title: "课程推荐", icon: "Guide", path: "/CourseRecommendation" });
      menuData.value.push({ id: 7, title: "用户管理", icon: "User", path: "/individual" });
      menuData.value.push({ id: 8, title: "用户反馈", icon: "Message", path: "/feedback" });
      menuData.value.push({ id: 9, title: "更新日志", icon: "Notification", path: "/updatelogs" });
      menuData.value.push({ id: 10, title: "教师工号", icon: "UserFilled", path: "/teachers" });
      menuData.value.push({ id: 11, title: "校历管理", icon: "Calendar", path: "/school-calendar" });
    }
    getSeigFrpStatus();

    // 设置对话框响应式宽度
    const setDialogWidth = () => {
      dialogWidth.value = window.innerWidth < 768 ? "90%" : "500px";
    };

    setDialogWidth();
    window.addEventListener("resize", setDialogWidth);

    // 组件卸载时移除事件监听
    onUnmounted(() => {
      window.removeEventListener("resize", setDialogWidth);
    });

    generateQRCode();
    loadMiniProgramCode();

    getWxBindStatus();
  });

  const visible = ref(false);
  const formRef = ref();
  const fileList = ref<any[]>([]);

  const form = reactive({
    content: "",
    contact: "",
    rating: 3
  });

  const rules = {
    content: [{ required: true, message: "请输入反馈内容", trigger: "blur" }],
    rating: [{ required: true, message: "请选择评分", trigger: "change" }]
  };

  const handleExceed = () => {
    ElMessage.warning("最多只能上传5张图片");
  };

  const submitForm = async () => {
    await formRef.value.validate();

    // 上传图片
    const images = await Promise.all(
      fileList.value.map(async (file: any) => {
        const formData = new FormData();
        // 确保文件对象是有效的
        if (file.raw) {
          formData.append("file", file.raw, file.raw.name || "image.png");
          return api.uploadFeedbackImage(formData);
        }
        return { data: { url: "" } }; // 如果文件不存在返回空值
      })
    );

    // 过滤空URL
    const validImages = images.filter((res: any) => res && res.data && res.data.url).map((res: any) => res.data.url);

    // 提交反馈
    await api.submitFeedback({
      ...form,
      images: validImages || []
    });

    ElMessage.success("提交成功，感谢您的反馈");
    visible.value = false;
    formRef.value.resetFields();
    fileList.value = [];
  };

  // 添加粘贴图片功能
  const handlePaste = async (event: ClipboardEvent) => {
    // 检查是否已达到上传限制
    if (fileList.value.length >= 5) {
      ElMessage.warning("最多只能上传5张图片");
      return;
    }

    const items = (event.clipboardData || (event as any).originalEvent.clipboardData).items;
    let hasImage = false;

    for (const item of items) {
      if (item.type.indexOf("image") === 0) {
        const blob = item.getAsFile();
        hasImage = true;

        // 如果添加这张图片会超过限制，则提示并退出
        if (fileList.value.length >= 5) {
          ElMessage.warning("最多只能上传5张图片");
          break;
        }

        // 创建预览
        const reader = new FileReader();
        reader.onload = e => {
          const file = {
            name: `pasted-image-${new Date().getTime()}.png`,
            raw: blob,
            url: e.target?.result
          };
          fileList.value.push(file);
        };
        reader.readAsDataURL(blob);
      }
    }

    if (hasImage) {
      ElMessage.success("图片已添加到上传列表");
      event.preventDefault();
    }
  };

  const dialogWidth = ref("500px");

  const qrCodeUrl = ref("");
  const recognitionCode = ref(localStorage.getItem("recognition_code") || "");

  const showQRCode = ref(true);

  const toggleQRCode = () => {
    showQRCode.value = !showQRCode.value;
  };

  const generateQRCode = async () => {
    if (recognitionCode.value) {
      try {
        qrCodeUrl.value = await QRCode.toDataURL(recognitionCode.value, {
          errorCorrectionLevel: "H",
          margin: 1,
          scale: 8,
          rendererOpts: {
            // 使用圆形点而非方形
            rounded: 100
          }
        });
      } catch (err) {
        console.error("生成二维码失败:", err);
      }
    }
  };

  const copyQRCode = () => {
    navigator.clipboard.writeText(recognitionCode.value);
    ElMessage.success("识别码已复制到剪贴板");
  };

  const miniprogramCodeUrl = ref("");

  const loadMiniProgramCode = async () => {
    // 先从localStorage获取缓存的小程序码
    const cachedMiniProgramCode = localStorage.getItem("miniProgramCode");

    if (cachedMiniProgramCode) {
      miniprogramCodeUrl.value = cachedMiniProgramCode;
    } else {
      try {
        const response = await api.getWxacode();
        if (response.data && response.data.code === 200 && response.data.data) {
          // 假设后端返回base64格式的图片数据
          const base64Image = response.data.data.img;
          miniprogramCodeUrl.value = `data:image/png;base64,${base64Image}`;
          // 保存到localStorage
          localStorage.setItem("miniProgramCode", miniprogramCodeUrl.value);
        } else {
          console.error("获取小程序码失败:", response.data);
        }
      } catch (error) {
        console.error("获取小程序码出错:", error);
      }
    }
  };

  const wxBindStatus = ref(false);

  // 获取微信小程序绑定状态
  const getWxBindStatus = async () => {
    try {
      const res = await api.getUserWxOpenidStatus();
      console.log(res.data);
      if (res.data.code === 200) {
        wxBindStatus.value = res.data.status;
      }
    } catch (error) {
      console.error("获取微信小程序绑定状态失败", error);
    }
  };

  // 处理解绑点击
  const handleUnbindClick = async () => {
    if (!wxBindStatus.value) return;

    try {
      const res = await api.unbindRecognitionCode();
      if (res.data.code === 200) {
        wxBindStatus.value = false;
        ElNotification({
          message: "解绑成功",
          position: "bottom-left",
          duration: 2000
        });
      }
    } catch (error) {
      console.error("解绑失败", error);
      ElNotification({
        message: "解绑失败，请重试",
        position: "bottom-left",
        duration: 2000
      });
    }
  };

  defineExpose({ visible });
</script>

<style scoped lang="less">
  .common-aside {
    position: fixed;
    top: 0;
    left: 0;
    width: 8%;
    height: 100vh;
    display: flex;
    flex-direction: column;

    transition: all 0.3s;

    // 禁止选中
    user-select: none;

    .menu-container {
      display: flex;
      flex-direction: column;
      height: 100%;
      background-color: #43497b;
    }

    .el-menu {
      border-right: none;
      flex: 1;
      overflow-y: auto;

      .menu-title {
        text-align: center;
        line-height: 52px;
        color: #fff;
        font-size: 14px;
        margin: 0;
        padding: 0;
      }

      .icons {
        width: 18px;
        height: 18px;
        margin-right: 5px;
      }

      :deep(.el-menu-item) {
        display: flex;
        justify-content: center;
        align-items: center;
        text-align: center;
        padding-left: 10px !important;

        .el-icon {
          margin-right: 5px;
        }

        span {
          flex: 0 1 auto;
          text-align: center;
        }
      }
    }

    .copyright {
      padding: 16px 8px;
      color: rgba(255, 255, 255, 0.7);
      text-align: center;
      background-color: #43497b;
      border-top: 1px solid rgba(255, 255, 255, 0.1);
      transition: all 0.6s;
      font-size: 12px;

      .status-group {
        margin-bottom: 12px;
        text-align: left;
      }

      .status-item {
        display: flex;
        align-items: center;
        margin-bottom: 6px;
        font-size: 12px;
        // 居中显示
        justify-content: center;

        .label {
          flex: 0 0 60px;
          color: rgba(255, 255, 255, 0.6);
        }

        .value {
          &::before {
            content: "";
            display: inline-block;
            width: 6px;
            height: 6px;
            border-radius: 50%;
            margin-right: 4px;
          }

          &.no-dot {
            &::before {
              display: none;
            }
            &:hover {
              cursor: pointer;
              color: #ffd04b;
            }
          }

          &.success {
            color: #67c23a;
            &::before {
              background: #67c23a;
            }
          }

          &.error {
            color: #f56c6c;
            &::before {
              background: #f56c6c;
            }
          }
        }
      }

      &.collapsed {
        padding: 12px 4px;

        .status-item {
          flex-direction: column;
          align-items: flex-start;
          margin-bottom: 8px;

          .label {
            flex: none;
            margin-bottom: 2px;
          }

          .value {
            margin-left: 0;
          }
        }

        .copyright-content {
          transform: scale(0.9);
        }
      }

      .qrcode-container {
        padding: 8px 0;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        margin-top: -10px;
        gap: 8px;

        .qrcode-title {
          color: #fff;
          font-size: 13px;
          padding: 4px 8px;
          background: rgba(255, 255, 255, 0.1);
          border-radius: 4px;
          margin-bottom: 4px;

          span {
            display: block;
            text-align: center;
          }
        }

        .qrcode-wrapper {
          position: relative;
          cursor: pointer;

          .qrcode-image {
            width: 100px;
            height: 100px;
            border-radius: 12px;
            padding: 6px;
            background: white;
            transition: all 0.3s ease;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          }

          &:hover {
            .qrcode-image {
              transform: scale(1.05);
              box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
            }
          }
        }
      }
    }
  }

  .el-col-3 {
    flex: 0 0 8%;
    max-width: 8%;
  }

  .feedback-dialog {
    :deep(.el-dialog__header) {
      padding: 20px 20px 10px;
      margin-right: 0;
      text-align: center;
      border-bottom: 1px solid #f0f0f0;
    }

    :deep(.el-dialog__title) {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }

    :deep(.el-dialog__body) {
      padding: 30px 25px;
    }

    :deep(.el-form-item__label) {
      font-weight: 500;
    }

    :deep(.el-dialog__footer) {
      padding: 10px 20px 20px;
      border-top: 1px solid #f0f0f0;
    }

    :deep(.el-upload--picture-card) {
      --el-upload-picture-card-size: 100px;
      border-radius: 8px;
      transition: all 0.3s;

      &:hover {
        border-color: var(--el-color-primary);
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }

    :deep(.el-upload-list__item) {
      border-radius: 8px;
      overflow: hidden;
    }

    :deep(.el-textarea__inner) {
      border-radius: 8px;
      padding: 12px;
      resize: none;
    }

    :deep(.el-input__wrapper) {
      border-radius: 8px;
    }

    :deep(.el-button) {
      border-radius: 8px;
      padding: 10px 20px;
    }
  }
</style>
